package com.aps.server.service;

import com.aps.common.service.TestGenericService;
import com.aps.server.context.ValidateContext;
import com.aps.server.dto.ApsCraftDto;
import com.aps.server.entity.ApsCraft;
import com.aps.server.entity.ApsOrder;
import com.aps.server.entity.BasicProduct;
import com.aps.server.mapper.ApsCraftMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工艺表 服务类
 * 
 * @author aps
 * @since 2024-01-01
 */
@Slf4j
@Service
public class ApsCraftService extends TestGenericService {

    @Resource
    ApsCraftMapper apsCraftMapper;

    /**
     * 创建工艺
     * @param apsCraft
     * @return
     */
    public boolean createCraft(ApsCraft apsCraft){
        // 自动设置租户ID
        if (apsCraft.getTenantId() == null || apsCraft.getTenantId().trim().isEmpty()) {
            apsCraft.setTenantId(getCurrentTenantId());
        }
        apsCraft.setCreateTime(LocalDateTime.now());
        apsCraft.setUpdateTime(LocalDateTime.now());
        if(StringUtils.isBlank(apsCraft.getCraftCode())) {
            //编码未填写
            return false;
        }
        List<ApsCraft> apsCrafts = queryApsCraftByOperationCode(Collections.singletonList(apsCraft.getCraftCode()));
        if(CollectionUtils.isEmpty(apsCrafts)) {
            //do insert
            int result = apsCraftMapper.insert(apsCraft);
            log.info("创建工艺信息结果: {}, 工艺ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", apsCraft.getId(), apsCraft.getTenantId());
            return result > 0;
        }
        log.info("创建工艺信息结果: {}, 存在相同的工艺code: {}, 租户ID: {}", "失败", apsCraft.getCraftCode(), apsCraft.getTenantId());
        return false;
    }

    //新增、编辑 校验编号是否存在，存在则返回对应 存在的数据
    public List<ApsCraft> queryApsCraftByOperationCode(List<String> craftCodes) {
        if(CollectionUtils.isEmpty(craftCodes)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<ApsCraft> craftLambdaQueryWrapper = new LambdaQueryWrapper<ApsCraft>()
                .eq(ApsCraft::getTenantId, getCurrentTenantId())
                .in(ApsCraft::getCraftCode, craftCodes);
        return apsCraftMapper.selectList(craftLambdaQueryWrapper);
    }



    //更新工艺信息
    public boolean updateCraft(ApsCraft apsCraft) {
        apsCraft.setUpdateTime(LocalDateTime.now());
        QueryWrapper<ApsCraft> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", apsCraft.getId()).eq("tenant_id", apsCraft.getTenantId());

        //查询原数据
        List<ApsCraft> basicOperationss = apsCraftMapper.selectList(
                Wrappers.lambdaQuery(ApsCraft.class)
                        .eq(ApsCraft::getId, apsCraft.getId())
                        .eq(ApsCraft::getTenantId, apsCraft.getTenantId()));
        ApsCraft original = basicOperationss.get(0);
        //编码没变过，直接修改
        if(StringUtils.equals(original.getCraftCode(), apsCraft.getCraftCode())) {
            int result = apsCraftMapper.update(apsCraft, queryWrapper);
            log.info("更新工艺信息结果: {}, 工艺ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", apsCraft.getId(), apsCraft.getTenantId());
            return result > 0;
        }
        //变过编码，需要校验一下编码
        List<ApsCraft> basicOperations = queryApsCraftByOperationCode(Collections.singletonList(apsCraft.getCraftCode()));
        if(CollectionUtils.isEmpty(basicOperations)) {
            //do insert
            int result = apsCraftMapper.update(apsCraft, queryWrapper);
            log.info("更新工艺信息结果: {}, 工艺ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", apsCraft.getId(), apsCraft.getTenantId());
            return result > 0;
        }
        log.info("更新工艺信息结果: {}, 存在相同的工艺code: {}, 租户ID: {}", "失败", apsCraft.getCraftCode(), apsCraft.getTenantId());
        return false;
    }


    /**
     * 删除工艺信息
     *
     * @param id 工艺ID
     * @return 是否删除成功
     */
    public boolean deleteCraft(String id) {
        String tenantId = getCurrentTenantId();
        return deleteCraft(id, tenantId);
    }

    /**
     * 根据ID和租户ID删除工艺信息
     *
     * @param id 工艺ID
     * @param tenantId 租户ID
     * @return 是否删除成功
     */
    public boolean deleteCraft(String id, String tenantId) {
        QueryWrapper<ApsCraft> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);

        int result = apsCraftMapper.delete(queryWrapper);
        log.info("删除工艺信息结果: {}, 工艺ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", id, tenantId);
        return result > 0;
    }



    /**
     * 查询当前租户的工艺对应工艺列表
     *
     * @return 产品列表
     */
    public List<ApsCraftDto> getCraftsByTenantId(String productCode,String productName,String craftName,String craftCode) {
        String tenantId = getCurrentTenantId();
        return getCraftsByTenantId(tenantId,productCode,productName ,craftName,craftCode);
    }

    /**
     * 根据租户ID查询产品列表
     *
     * @param tenantId 租户ID
     * @return 产品列表
     */
    private List<ApsCraftDto> getCraftsByTenantId(String tenantId,String productCode,String productName,String craftName,String craftCode) {
        ApsCraftDto queryParam = new ApsCraftDto();
        queryParam.setTenantId(tenantId);
        queryParam.setProductCode(productCode);
        queryParam.setProductName(productName);
        queryParam.setCraftCode(craftCode);
        queryParam.setCraftName(craftName);
        List<ApsCraftDto> craftsByTenantId = apsCraftMapper.getCraftsByTenantId(queryParam);
        log.info("根据租户ID查询工艺工艺列表, 租户ID: {}, 数量: {}", tenantId, craftsByTenantId.size());
        return craftsByTenantId;
    }

    /**
     * 按照产品id  查询产品是否存在工艺
     */
    public void craftCheck(List<BasicProduct> products , ValidateContext context) {
        creaftInfoCheck(products.stream().map(BasicProduct::getId).distinct().toList(), context);
    }

    private void creaftInfoCheck(List<String> productsIds , ValidateContext context) {
        LambdaQueryWrapper<ApsCraft> productQ = new LambdaQueryWrapper<ApsCraft>()
                .eq(ApsCraft::getTenantId, getCurrentTenantId())
                .in(ApsCraft::getCraftProductId, productsIds);
        List<ApsCraft> crafts = apsCraftMapper.selectList(productQ);
        context.setApsCrafts(crafts);
    }
}
